package com.briup.web.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.ibatis.session.SqlSession;

import com.briup.common.bean.TblArticle;
import com.briup.common.bean.TblCategory;
import com.briup.common.util.MyBatisSqlSessionFactory;
import com.briup.service.impl.TblArticleServiceImpl;

/**
 * Servlet implementation class toContent_Servlet
 */
@WebServlet("/jsp/toContent_Servlet")
public class toContent_Servlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public toContent_Servlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String id = request.getParameter("id") ;
		int clicktimes = 0 ;
			
		List<TblArticle> articles = (List<TblArticle>) request.getSession().getAttribute("articles") ;
		for (int i = 0; i < articles.size() ; i++) {
			if (id.equals(String.valueOf(articles.get(i).getId()))) {
				request.getSession().setAttribute("article", articles.get(i));
				clicktimes = articles.get(i).getClicktimes() ;
				articles.get(i).setClicktimes(++clicktimes);
			}
		}
		
		SqlSession openSession = MyBatisSqlSessionFactory.openSession() ;
		try {
			TblArticleServiceImpl tblArticleServiceImpl = new TblArticleServiceImpl() ;
			int i = tblArticleServiceImpl.updateArticleClickTimesByid(openSession, id, clicktimes) ;
			if (i == 1) {
				openSession.commit();
			}else {
				openSession.rollback();
			}
		} catch(Exception e) {
			openSession.rollback();
			System.out.println(e.getCause().toString());
			e.printStackTrace();
		}finally {
			openSession.close();
			response.sendRedirect("content.jsp");
		}
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
